<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useMessage, NFlex, NButton, NGrid, NGi, NFormItem, NCheckbox } from 'naive-ui';
import { createProForm, zhCN, ProCard } from 'pro-naive-ui';
import { $t } from '@/locales';
import ConfigProvider from '../../ConfigProvider.vue';

import { fetchGetConfigList, fetchSaveConfig, type Api } from '@/service/api/logistics';

const message = useMessage();
const submitting = ref(false);
const configGroups = ref<Api.Config.ConfigGroup[]>([]);
const formValues = reactive<Api.Config.SaveConfigRequest>({});

const form = createProForm<Api.Config.SaveConfigRequest>({
  initialValues: {},
  onSubmit: async (values) => {
    try {
      submitting.value = true;
      await fetchSaveConfig(values);
      message.success($t('page.system_config.save_success'));
    } catch (error) {
      message.error($t('page.system_config.save_fail'));
    } finally {
      submitting.value = false;
    }
  },
  onReset: () => {
    message.success($t('page.system_config.reset_success'));
    initFormValues(configGroups.value);
  }
});

function initFormValues(groups: Api.Config.ConfigGroup[]) {
  Object.keys(formValues).forEach(key => delete formValues[key]);

  groups.forEach(group => {
    const groupParams: Record<string, boolean> = {};
    group.params.forEach(param => {
      groupParams[param.paramKey] = param.defaultValue;
    });
    formValues[group.groupKey] = groupParams;
  });

  form.values.value = { ...formValues };
}

const loadConfigList = async () => {
  try {
    submitting.value = true;
    const { data } = await fetchGetConfigList();
    const validGroups = Array.isArray(data) ? data : [] as Api.Config.ConfigGroup[];
    configGroups.value = validGroups;
    initFormValues(validGroups);
  } catch (error) {
    message.error($t('page.system_config.load_fail'));
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  loadConfigList();
});

const getFormGroupValue = (groupKey: string) => {
  return form.values.value[groupKey] as Record<string, boolean>;
};

const updateFormParamValue = (groupKey: string, paramKey: string, value: boolean) => {
  const group = getFormGroupValue(groupKey);
  if (group) {
    group[paramKey] = value;
    form.values.value = { ...form.values.value };
  }
};
</script>

<template>
  <ConfigProvider :locale="zhCN">
    <ProForm :form="form" :loading="submitting">
      <ProCard :title="$t('page.system_config.page_title')" :show-collapse="false">
        <template #header-extra>
          <NFlex gap="12px" align="center">
            <NButton attr-type="reset" type="default">
              {{ $t('page.system_config.reset') }}
            </NButton>
            <NButton attr-type="submit" type="primary" :loading="submitting">
              {{ $t('page.system_config.save') }}
            </NButton>
          </NFlex>
        </template>

        <div v-if="configGroups.length > 0">
          <div v-for="group in configGroups" :key="group.groupKey" class="config-group">
            <h3 class="group-title">{{ group.groupName }}</h3>
            <NGrid cols="1" :x-gap="16" class="param-grid">
              <NGi v-for="param in group.params" :key="param.paramKey">
                <NFormItem :label="''" :tooltip="param.description || ''" class="param-item">
                  <div class="checkbox-wrapper">
                    <NCheckbox :checked="getFormGroupValue(group.groupKey)[param.paramKey]"
                      @update:checked="(value) => updateFormParamValue(group.groupKey, param.paramKey, value)"
                      class="checkbox" />
                    <span class="param-text">{{ param.paramName }}</span>
                  </div>
                </NFormItem>
              </NGi>
            </NGrid>
          </div>
        </div>
      </ProCard>
    </ProForm>
  </ConfigProvider>
</template>

<style scoped>
.config-group {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.group-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.param-grid {
  margin-left: 8px;
}

.param-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox {
  margin-right: 8px;
}

.param-text {
  font-size: 14px;
  color: #333;
  line-height: 1;
}

.empty-tip {
  padding: 40px;
  text-align: center;
  color: #666;
}
</style>
